<template>
  <canvas id="canvas"></canvas>
  <div class="login-bg">
    <div class="login-box">
      <img class="login-img" alt="login bg" src="./bg.png" />
      <h1>7星连珠，召唤神龙 ~ GitHub登录</h1>
      <div
        class="bling-star no-animation"
        v-for="item in 7"
        :key="`bling-star-${item}`"
        :style="`left: ${50 * (8 - item) + 30}px;top: ${
          40 * item + 50
        }px; background-color: ${randomRgbColor()};box-shadow: 0 0 8px 8px ${randomRgbColor()}, inset 0 -5px 5px 0 #fff;`"
      >
        {{ 8 - item }}
      </div>
      <el-button
        type="primary"
        @click="login"
        :loading="loading"
        class="login-button"
        >GitHub登录</el-button
      >
      <!-- <el-button type="primary" @click="getUserInfo">获取用户信息</el-button> -->
    </div>
  </div>
</template>

<script>
import { githubToken, githubUserInfo, myLogin } from "@/api/login.js";
import { onMounted, reactive, toRefs } from "@vue/runtime-core";
import { starsky } from "./star.js";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
export default {
  name: "Login",
  setup() {
    const state = reactive({
      loading: false,
    });
    const router = useRouter();
    onMounted(() => {
      const urlSearch = window.location.search.replace("?", "");
      const code = urlSearch.includes("code") ? urlSearch.split("=")[1] : "";
      starsky();
      if (code.length !== 0) {
        removeNoAnimation();
        state.loading = true;
        window.history.pushState(
          {},
          0,
          `${window.location.protocol}//${window.location.host}/#/login?code=${code}`
        );
        process.env.NODE_ENV === "production"
          ? loginNext(code)
          : getGitHubToken(code);
      }

      const starEle = document.getElementsByClassName("bling-star");
      starEle.forEach((element, i) => {
        if (i === 0 || i === 6) {
          drag(element);
        }
      });
    });

    function resetCss() {
      const starEle = document.getElementsByClassName("bling-star");
      console.log(starEle);
      starEle.forEach((element, i) => {
        element.style.left = `${50 * (8 - i)}px`;
        element.style.top = `${0}200px`;
        // element.style.animation = "none";
        element.classList.add("line");
        element.classList.add("no-animation");
      });
    }

    function firstCss() {
      const starEle = document.getElementsByClassName("bling-star");
      starEle.forEach((element, i) => {
        element.style.left = `${50 * (8 - i)}px`;
        element.style.top = `${40 * i + 50}px`;
        element.classList.add("no-animation");
      });
    }

    function removeNoAnimation() {
      const starEle = document.getElementsByClassName("bling-star");
      starEle.forEach((element) => {
        element.classList.remove("no-animation");
      });
    }

    // function moveEle(element, translate) {
    //   // let x0, y0;
    //   // let ex = 0, ey = 0;
    //   console.log("==", element);
    //   element.style.transform = translate;
    // }

    function drag(element) {
      let x0, y0;
      let ex = 0,
        ey = 0;
      let move = (e) => {
        console.log("move", e.clientX - x0, e.clientY - y0, x0, y0, ex, ey);
        let [dx, dy] = [e.clientX - x0, e.clientY - y0];
        // if (dx >= 50 && -dy >= 40) {
        //   console.log(typeof eles);
        //   // let ele = eles.filter(
        //   //   (item) =>
        //   //     item.offsetLeft > element.offsetLeft &&
        //   //     item.offsetTop > element.offsetTop
        //   // );
        //   for (let i = 0; i < eles.length; i++) {
        //     const item = eles[i];
        //     console.log(item);
        //     if (
        //       item.offsetLeft > element.offsetLeft &&
        //       item.offsetTop > element.offsetTop
        //     ) {
        //       console.log("--item", item);
        //     }
        //   }
        //   // moveEle(ele, `translate(${ex + dx}px, ${ey + dy}px)`);
        // }
        element.style.transform = `translate(${ex + dx}px, ${ey + dy}px)`;
      };
      let up = (e) => {
        document.removeEventListener("mousemove", move);
        document.removeEventListener("mouseup", up);
        let [dx, dy] = [e.clientX - x0, e.clientY - y0];
        element.style.transform = `translate(${ex + dx}px, ${ey + dy}px)`;
        (ex += dx), (ey += dy);
      };
      element.addEventListener("mousedown", (e) => {
        console.log("down");
        [x0, y0] = [e.clientX, e.clientY];
        document.addEventListener("mousemove", move);
        document.addEventListener("mouseup", up);
      });
    }

    function loginNext(code) {
      myLogin({ code }).then((res) => {
        if (res.retCode === 0) {
          this.$message.success("登录成功");
        }
      });
    }
    function login() {
      removeNoAnimation();
      state.loading = true;
      const authorizeUri = "https://github.com/login/oauth/authorize";
      // Client ID 685f3527e17831834986
      // Client secrets b8ae8ba6f4681a44068760c60f7d79beee3afcfb
      const clientID = "685f3527e17831834986";
      const redirectUri = "http://localhost:8080/#/login";
      window.location.href = `${authorizeUri}?client_id=${clientID}&redirect_uri=${redirectUri}`;
    }
    function getGitHubToken(code) {
      const params = {
        client_id: "685f3527e17831834986",
        client_secret: "b8ae8ba6f4681a44068760c60f7d79beee3afcfb",
        code,
      };
      githubToken(params)
        .then((res) => {
          let token = "";
          if (res && res.includes("access_token")) {
            token = res
              .split("&")
              .filter((item) => item.includes("access_token"))[0]
              .split("=")[1];
          }
          state.loading = false;
          console.log("----token:", token);
          if (token) {
            localStorage.setItem("token", token);
            resetCss();
            ElMessage.success("神龙召唤成功!");
            getUserInfo();
            setTimeout(() => {
              router.push("/");
            }, 2000);
          }
          token === "" && firstCss();
          token === "" && ElMessage.warning("神龙召唤失败，GitHub登录失败");
        })
        .catch((e) => {
          state.loading = false;
          console.log("github faild", e);
        });
    }

    function getUserInfo() {
      resetCss();
      githubUserInfo().then((res) => {
        console.log(res);
        ElMessage.success("欢迎神龙~ " + res.login);
      });
    }

    function randomRgbColor() {
      //随机生成RGB颜色
      var r = Math.floor(Math.random() * 256); //随机生成256以内r值
      var g = Math.floor(Math.random() * 256); //随机生成256以内g值
      var b = Math.floor(Math.random() * 256); //随机生成256以内b值
      return `rgb(${r},${g},${b})`; //返回rgb(r,g,b)格式颜色
    }

    return {
      ...toRefs(state),
      login,
      getUserInfo,
      randomRgbColor,
    };
  },
};
</script>

<style lang="scss" scoped>
#canvas {
  z-index: -100;
  position: absolute;
  left: 0;
  top: 0;
  background-color: #000;
}

.bling-star {
  position: absolute;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  background-color: lightpink;
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  margin: 5px;
  box-shadow: 0 0 10px 10px #00a2ff;
  animation: action 2s linear infinite;
}
.bling-star:nth-child(1) {
  animation: action 1s linear infinite;
}
.bling-star:nth-child(2) {
  animation: action 1.5s linear infinite;
}
.bling-star:nth-child(3) {
  animation: action 2s linear infinite;
}
.bling-star:nth-child(4) {
  animation: action 2.5s linear infinite;
}
.bling-star:nth-child(5) {
  animation: action 3s linear infinite;
}
.bling-star:nth-child(6) {
  animation: action 3.5s linear infinite;
}
.bling-star:nth-child(7) {
  animation: action 4s linear infinite;
}
.no-animation {
  animation: none !important;
}
.line {
  top: 200px !important;
}
@keyframes spin {
  to {
    transform: rotate(1turn);
  }
}
@keyframes action {
  from {
    transform: rotate(0deg) translate(100px) rotate(0deg);
  }
  to {
    transform: rotate(360deg) translate(100px) rotate(-360deg);
  }
}

.login-bg {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: gainsboro;
  background-color: rgba(92, 112, 131, 0.2);
  .login-box {
    position: absolute;
    top: 50%;
    left: 50%;
    border-radius: 20px;
    background-color: rgba($color: #000000, $alpha: 0.4);
    .login-img {
      position: absolute;
      right: 10px;
      bottom: 10px;
      // width: 30vw;
      // height: 20vh;
    }
    .login-button {
      position: absolute;
      bottom: 60px;
      right: 90px;
      box-shadow: 0 0 5px 5px #f8f53f;
    }
    .el-button--primary {
      color: #fff;
      font-weight: bold;
      background-color: sandybrown;
    }
    h1 {
      -webkit-background-clip: text;
      background-clip: text;
      background-image: -webkit-gradient(
        linear,
        left top,
        right top,
        from(#09f1b8),
        color-stop(#00a2ff),
        color-stop(#ff00d2),
        to(#fed90f)
      );
      background-image: -o-linear-gradient(
        left,
        #09f1b8,
        #00a2ff,
        #ff00d2,
        #fed90f
      );
      background-image: linear-gradient(
        to right,
        #09f1b8,
        #00a2ff,
        #ff00d2,
        #fed90f
      );
      color: #000119;
      color: var(--color-background);
      // font-size: 20vmin;
      // font-size: var(--font-size);
      font-weight: 700;
      font-weight: var(--font-weight);
      letter-spacing: calc(1em / 8);
      letter-spacing: var(--letter-spacing);
      padding: calc(2);
      -webkit-text-stroke-color: transparent;
      -webkit-text-stroke-width: calc(1em / 16);
      -webkit-text-stroke-width: var(2);
    }
  }
  @media screen and (min-width: 576px) {
    .login-box {
      width: 50vw;
      height: 50vh;
      margin-top: -25vh;
      margin-left: -25vw;
      .login-img {
        height: 20vh;
      }
    }
  }
  @media screen and (max-width: 575px) {
    .bling-star {
      transform: translate(-80px);
    }
    .login-box {
      width: 90vw;
      height: 60vh;
      margin-top: -30vh;
      margin-left: -45vw;
      .login-img {
        width: 60vw;
      }
      .login-button {
        position: absolute;
        bottom: 100px;
        right: 5vw;
        box-shadow: 0 0 5px 5px #f8f53f;
      }
    }
  }
}
</style>
